package com.kalix.training.message.biz;

import com.kalix.framework.core.api.persistence.JsonData;
import com.kalix.framework.core.impl.biz.ShiroGenericBizServiceImpl;
import com.kalix.training.message.api.biz.IMessageBeanService;
import com.kalix.training.message.api.dao.IMessageBeanDao;
import com.kalix.training.message.api.dto.AllMessageDTO;
import com.kalix.training.message.api.dto.MessageDTO;
import com.kalix.training.message.entities.MessageBean;

import java.util.List;

public class MessageBeanServiceImpl extends ShiroGenericBizServiceImpl<IMessageBeanDao, MessageBean>
        implements IMessageBeanService {
    /**
     * 根据cid查询所有留言
     * @param id
     * @return
     */
    @Override
    public JsonData getMesByCid(long id) {
        String sql = "Select m.id,m.cid,m.content,m.score,m.creationDate,u.icon,u.name as uname from mooc_message m,sys_user u where m.uid = u.id and  m.cid = " + id + " order by m.creationDate desc";
        List<MessageDTO> list = dao.findByNativeSql(sql, MessageDTO.class);
        JsonData jsonData = new JsonData();
        jsonData.setData(list);
        jsonData.setTotalCount((long)list.size());
        return jsonData;
    }

    @Override
    public JsonData getAllMessage(Integer page, Integer limit, String jsonStr) {
//        String sql = "Select m.id,m.cid,m.uid,c.name as cname,m.content,m.score,c.did from mooc_message m, mooc_course c, sys_user u where m.cid=c.id and m.uid=u.id";
        String sql ="Select m.id,m.cid,m.uid,c.name as cname,m.content,m.score,c.did from mooc_message m, mooc_course c where m.cid=c.id";
        List<AllMessageDTO> list = dao.findByNativeSql(sql, AllMessageDTO.class);
        JsonData jsondata = new JsonData();
        if (list.size() > 0) {
            if (page != null && limit != null) {
                List<AllMessageDTO> mlist = list.subList(page * limit - limit, limit * page > list.size() ? list.size() : limit * page);
                jsondata.setData(mlist);
                jsondata.setTotalCount((long) list.size());
            } else {
                jsondata.setData(list);
                jsondata.setTotalCount((long) list.size());
            }
        }
        return jsondata;

    }
}
